<?php
/**
 * @Author:      lyt
 * @DateTime:  2017-06-16 15:13:34
 * @Description: 用于系统的 记录
 */
class WposRecord extends Eloquent
{
    protected $table = "wpos_record";


    public static $pay_type=array(
    	1001=>1,
		1003=>3,
		1004=>2,
		1005=>16,
		1006=>7,
		1007=>17,
		1009=>18,
		1011=>19,
    );

    public static $pay_type_change=array(
    	1=>1001,
		3=>1003,
		2=>1004,
		16=>1005,
		7=>1006,
		17=>1007,
		18=>1009,
		19=>1011,
    );


     /**
     * @Author:      lyt
     * @DateTime:  2017-06-16 15:25:34
     * @Description: 调用pos 生成订单
     * @params type 支付的类型
     * @params order_id 业务单号
     * @params buss_id 业务单支付号
     * @params amount 支付金额
     * @params user_id 用户id
     * @params shop_id 门店id
     * @params device_en 设备号
     * @params create_by 创建人
     */
    public static function prepareOrder($type,$order_id,$buss_id,$amount,$user_id,$shop_id,$device_en,$create_by,$pay_type=0,$call_scan=0){        
        try{
            return  DB::transaction(function() use ($type,$order_id,$buss_id,$amount,$user_id,$shop_id,$device_en,$create_by,$pay_type,$call_scan) {         
		        $desc = '';
		        $attach = '';
		        switch ($type) {
		        	case 1:
		        		$attach = '充值记录'.$order_id;
		        		$desc = '充值';
		        		break;
		        	case 2:
		        		$attach = '订单支付'.$order_id;
		        		$desc = '订单支付';
		        		break;
		        	case 3:
		        		$attach = '洗车单支付'.$order_id;
		        		$desc = '洗车单支付';
		        		break;
		        	case 4:
		        		$attach = '收回单支付'.$order_id;
		        		$desc = '收回单支付';
		        		break;
		        	case 5:
		        		$attach = '套餐卡订单支付'.$order_id;
		        		$desc = '套餐卡订单支付';
		        		break;
		        }
		        $mpd=MaintenancePosDevice::where("device_no",$device_en)->where('shop_id',$shop_id)->where('status',1)->first();
		        $pay_type=isset(WposRecord::$pay_type_change[$pay_type])?WposRecord::$pay_type_change[$pay_type]:0;//如果指定了支付方式 转换支付方式记录没有制定支付方式一定是 扫一扫
		        $id=Common::createOrderId();
		        $wr=new WposRecord;
		        $wr->id=$id;
		        $wr->type=$type;
		        $wr->buss_id=$buss_id;
		        $wr->amount=$amount;
		        $wr->user_id=$user_id;
		        $wr->shop_id=$shop_id;
		        $wr->create_by=$create_by;
		        $wr->seq_no="";
		        $wr->kingdee_code=isset($mpd->kingdee_code)?$mpd->kingdee_code:"";
		        $wr->pay_type=$pay_type;
		        $wr->save();
		        $response = Pos::prepareOrder($device_en,$id,$amount,$desc,$attach,$pay_type,$call_scan);
		        if($response->status!=0){
		        	return false;
		        }else{ //增加记录 消息ID
                    $wr2 = WposRecord::where('id',$id)->first();
                    $wr2->seq_no = $response->data->seq_no;
                    $wr2->save();
                }
		        return true;
            });
        } catch (Exception $e) {
            Log::error("error", array("system" => "Account" ,"event" => "prepareOrder" ,"exception" => $e));
            return false;
        }	    
    }	



    /**
     * @Author:      lyt
     * @DateTime:  2017-06-16 15:47:18
     * @Description: 回复业务
     */
    public static function notifyOrder($data){
    	try{
            return DB::transaction(function() use ($data){
          		$wr=WposRecord::find($data["out_trade_no"]);
		        if($wr&&$wr->amount==$data["total_fee"]){		            
		            $wr->cashier_trade_no=$data["cashier_trade_no"];
		            $wr->mcode=$data["mcode"];
		            $wr->device_en=$data["device_en"];
		            $wr->trade_status=$data["trade_status"];
		            $wr->pay_info=$data["pay_info"];
		            $wr->attach=isset($data["attach"])?$data["attach"]:"";
		            $wr->pay_type=$data["pay_type"];
		            $wr->pay_fee=$data["pay_fee"];
		            $wr->check_fee=$data["check_fee"];
		            $wr->thirdDiscount=$data["thirdDiscount"];
		            $wr->thirdMDiscount=$data["thirdMDiscount"];
		            $wr->time_end=$data["time_end"];
		            $wr->buyer=isset($data["buyer"])?$data["buyer"]:"";
		            $wr->thirdSerialNo=isset($data["thirdSerialNo"])?$data["thirdSerialNo"]:"";
		            $wr->terminalNo=isset($data["terminalNo"])?$data["terminalNo"]:"";
		            $wr->vouchNo=isset($data["vouchNo"])?$data["vouchNo"]:"";
		            $wr->batchNo=isset($data["batchNo"])?$data["batchNo"]:"";
		            $wr->cardType=isset($data["cardType"])?$data["cardType"]:"";
		            $wr->implement_time=Common::currentTimeString();
		            $wr->save();
		            $result = array(
				        'code' => 0,		
				        'type' => 0,		        
			            'order_id' => 0,
			            'buss_id' => 0,
				    );
		            $pay_type=WposRecord::$pay_type[$data["pay_type"]];
		            switch ($wr->type) {
			        	case 1://充值
			        		$tran_no = date('YmdHis',time()).Common::generateCode(8);   
			        		$aur=AcountUserRecharge::find($wr->buss_id);
			        		if($aur->status!=5){
			        			return 'fail';
			        		}
			        		$status=$data["trade_status"]=="PAY"?1:2;
			        		AcountUserRecharge::where("id",$wr->buss_id)->update(array("status"=>$status,"implement_time"=>Common::currentTimeString(),"tran_no"=>$tran_no,"pay_type"=>$pay_type,"pay_id"=>$wr->id));
			        		$aur=AcountUserRecharge::find($wr->buss_id);
			        		if($status==1){
			        			Account::record($aur->user_id,$aur->shop_id,1,$tran_no,1,121,$aur->amount,'pos充值收入,充值记录:'.$aur->id);
						    }
						    $result = array(
						        'code' => $status,
						        'type' => 1,		        
					            'order_id' => $aur->id,
					            'buss_id' => $wr->buss_id,
						    );
			        		break;
			        	case 2://订单支付 处理订单逻辑
			        		$tran_no = date('YmdHis',time()).Common::generateCode(8);   
			        		$op=OrderPay::find($wr->buss_id);
			        		$order = Orders::where("order_id",$op->order_id)->first();
			        		if($op->status!=5){
			        			return 'fail';
			        		}

			        		$status=$data["trade_status"]=="PAY"?1:2;
			        		OrderPay::where("id",$wr->buss_id)->update(array("status"=>$status,"implement_time"=>Common::currentTimeString(),"tran_no"=>$tran_no,"pay_type"=>$pay_type,"pay_id"=>$wr->id));
			        		if($status==1){
			        			//记录用户收入
				        		Account::record($order->pay_user_id,$order->shop_id,1,$tran_no,1,102,$op->amount,'订单结算充值,订单号:'.$order->order_id);
					            //记录用户支出
					            Account::record($order->pay_user_id,$order->shop_id,1,$tran_no,2,202,$op->amount,'订单结算支出,订单号:'.$order->order_id);
					            //记录公司账户收入
					            Account::record_base('1',$tran_no,1,102,$op->amount,'订单结算收入,订单号:'.$order->order_id);
					            //记录订单账务关系
					            OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));

				        		$op_arr=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(0,1,5))->get();
						        $order->payable_amount=$order->payable_amount+$op->amount;
						        $order->pay_type=sizeof($op_arr)==1?$pay_type:9;
						        // $order->pay_time=date("Y-m-d H:i:s",time()+Config::get("config.report_time_diff"));
						        $order->save();
						    }
						    $result = array(
						        'code' => $status,
						        'type' => 2,		        
					            'order_id' => $order->order_id,
					            'buss_id' => $wr->buss_id,
						    );
			        		break;
			        	case 3://洗车单支付
			        		$tran_no = date('YmdHis',time()).Common::generateCode(8);
                            $cwopr=CarWashOrderPayRecord::find($wr->buss_id); 
                            $cwo=CarWashOrder::find($cwopr->order_id);                             
                            if($cwopr->status!=5){
			        			return 'fail';
			        		}
                           
                            $status=$data["trade_status"]=="PAY"?1:2;
                            CarWashOrderPayRecord::where("id",$wr->buss_id)->update(array("status"=>$status,"implement_time"=>Common::currentTimeString(),"tran_no"=>$tran_no,"pay_type"=>$pay_type,"pay_id"=>$wr->id)); 
                            if($status==1){
                            	//记录用户充值 不记录充值记录  只记录流水
	                            Account::record($cwo->user_id,$cwo->shop_id,1,$tran_no,1,106,$cwopr->amount,'洗车单结算充值,洗车单号:'.$cwo->order_id);
	                            //记录用户支出
	                            Account::record($cwo->user_id,$cwo->shop_id,1,$tran_no,2,206,$cwopr->amount,'洗车单结算支出,洗车单号:'.$cwo->order_id);
	                            //记录公司账户收入
	                            Account::record_base('1',$tran_no,1,106,$cwopr->amount,'洗车单结算收入,洗车单号:'.$cwo->order_id);
	                            //记录订单账务关系
	                            CarWashOrderAccount::insert(array('order_id' => $cwo->order_id,'tran_no' => $tran_no,));

                            	$cwo->pay_type=$pay_type;
						        $cwo->pay_time=date("Y-m-d H:i:s",time()+Config::get("config.report_time_diff"));
						        $cwo->status=1417;
						        $cwo->save();

						        $order_flows = new CarWashOrderFlows;
			                    $order_flows->order_id = $cwo->order_id;
			                    $order_flows->status =1417;
			                    $order_flows->user_id = 0;
			                    $order_flows->type = 'sc';
			                    $order_flows->save();


			                    //积分返还
						        if(in_array($pay_type,CarWashOrderPayRecord::$ei_pay_type)){//说明是返回积分的支付类型
						            $mc=MemberCoefficient::where("source",4)->where("status",1)->first();
						            $ms=MaintenanceShops::find($cwo->shop_id);
						            UserIntegralFlow::record($cwo->user_id,$cwo->shop_id,$cwo->order_id,1,1004,floor($cwopr->amount*$mc->integral*$ms->integral/100),'洗车订单完成积分');
						            UserExperienceFlow::record($cwo->user_id,$cwo->shop_id,$cwo->order_id,1,1004,floor($cwopr->amount*$mc->experience*$ms->experience/100),'洗车订单完成经验');
						            Users::checkMember($cwo->user_id);
						        }
                            }        
                            $result = array(
						        'code' => $status,
						        'type' => 3,		        
					            'order_id' => $cwo->order_id,
					            'buss_id' => $wr->buss_id,
						    );                    
			        		break;
			        	case 4://收回单
			        		$tran_no = date('YmdHis',time()).Common::generateCode(8);   
			        		$op=ReceivablePay::find($wr->buss_id);
			        		$receivable = Receivable::find($op->receivable_id);
			        		if($op->status!=5){
			        			return 'fail';
			        		}
			        		$status=$data["trade_status"]=="PAY"?1:2;
			        		ReceivablePay::where("id",$wr->buss_id)->update(array("status"=>$status,"implement_time"=>Common::currentTimeString(),"tran_no"=>$tran_no,"pay_type"=>$pay_type,"pay_id"=>$wr->id));
			        		if($status==1){
			        			if($receivable->type==2){//如果是起初回收
			        				$ba=BeginArrear::where("shop_id",$receivable->shop_id)->where("company_id",$receivable->company_id)->lockForUpdate()->first();
			        				Account::record($receivable->company_id,0,3,$tran_no,1,118,$op->amount,'期初收回收入,收回单号:'.$receivable->receivable_id);
					                //记录用户收入
					                Account::record_base('1',$tran_no,1,118,$op->amount,'期初收回收入,收回单号:'.$receivable->receivable_id);
					                $ba->current_amount=$ba->current_amount-$op->amount;
            						$ba->save();
			        			}else{//如果是订单回收
			        				//记录用户充值 不记录充值记录  只记录流水
					                Account::record($receivable->company_id,0,3,$tran_no,1,114,$op->amount,'订单收回收入,收回单号:'.$receivable->receivable_id);
					                //记录用户支出
					                Account::record_base('1',$tran_no,1,114,$op->amount,'订单收回收入,收回单号:'.$receivable->receivable_id);
			        			}
			        			$op_arr=ReceivablePay::where("receivable_id",$receivable->receivable_id)->whereIn("status",array(0,1,5))->get();
						        $receivable->pay_type=sizeof($op_arr)==1?$pay_type:9;
						        $receivable->save();
						    }
						    $result = array(
						        'code' => $status,
						        'type' => 4,		        
					            'order_id' => $op->receivable_id,
					            'buss_id' => $wr->buss_id,
						    ); 
			        		break;
			        	case 5://套餐卡订单支付
			        		$tran_no = date('YmdHis',time()).Common::generateCode(8);   
			        		$op=ServiceCardOrderPayRecord::find($wr->buss_id);
			        		$order = ServiceCardOrder::where("order_id",$op->order_id)->first();
			        		if($op->status!=5){
			        			return 'fail';
			        		}
			        		$status=$data["trade_status"]=="PAY"?1:2;
			        		ServiceCardOrderPayRecord::where("id",$wr->buss_id)->update(array("status"=>$status,"implement_time"=>Common::currentTimeString(),"tran_no"=>$tran_no,"pay_type"=>$pay_type,"pay_id"=>$wr->id));
			        		if($status==1){
			        			//记录用户收入
				        		Account::record($order->user_id,$order->shop_id,1,$tran_no,1,123,$op->amount,'套餐卡订单结算充值,订单号:'.$order->order_id);
					            //记录用户支出
					            Account::record($order->user_id,$order->shop_id,1,$tran_no,2,223,$op->amount,'套餐卡订单结算支出,订单号:'.$order->order_id);
					            //记录公司账户收入
					            Account::record_base('1',$tran_no,1,123,$op->amount,'套餐卡订单结算收入,订单号:'.$order->order_id);
					            //记录订单账务关系
					            ServiceCardOrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));

				        		$op_arr=ServiceCardOrderPayRecord::where("order_id",$order->order_id)->whereIn("status",array(0,1,5))->get();
						        $order->pay_amount=$order->pay_amount+$op->amount;
						        $order->pay_type=sizeof($op_arr)==1?$pay_type:9;
						        $order->save();
						    }
						    $result = array(
						        'code' => $status,
						        'type' => 5,		        
					            'order_id' => $order->order_id,
					            'buss_id' => $wr->buss_id,
						    ); 
			        		break;
				    }
				    RedisHelper::push($result);
				    return 'success';    
				    
		        }else{
		            return 'fail';
		        }		        
            });
        } catch (Exception $e) {
            Log::error("error", array("system" => "Account" ,"event" => "prepareOrder" ,"exception" => $e));
            return 'fail';
        }       
        
    }
}